package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.EquipmentDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.PlantationDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Equipment;
import edu.ynu.se.xiecheng.achitectureclass.entity.Plantation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Arrays;

@Service
public class EquipmentService extends LogicService<EquipmentDao, Equipment, Long> {

    @Autowired
    private PlantationDao plantationDao;

    @Autowired
    private EquipmentDao equipmentDao;

    public EquipmentService(@Autowired EquipmentDao dao) {
        super(dao);
    }

    /**
     * 查询单个设备信息
     */
    public Equipment getEquipmentInfo(Long id) throws Exception {
        return dao.findById(id)
                .orElseThrow(() -> new Exception("设备不存在"));
    }

    /**
     * 更新设备信息
     * 只更新非null字段，保留原有值
     */
    public Equipment updateEquipment(Equipment equipment) throws Exception {
        // 获取原有设备信息
        Equipment existingEquipment = dao.findById(equipment.getId())
                .orElseThrow(() -> new Exception("设备不存在"));

        // 验证必填字段
        if (equipment.getEquipmentName() != null) {
            if (equipment.getEquipmentName().trim().isEmpty()) {
                throw new Exception("设备名称不能为空");
            }
            existingEquipment.setEquipmentName(equipment.getEquipmentName());
        }

        // 更新其他字段（只更新非null值）
        if (equipment.getEquipmentSerial() != null) {
            existingEquipment.setEquipmentSerial(equipment.getEquipmentSerial());
        }
        if (equipment.getFboxNumber() != null) {
            existingEquipment.setFboxNumber(equipment.getFboxNumber());
        }
        if (equipment.getEquipmentType() != null) {
            existingEquipment.setEquipmentType(equipment.getEquipmentType());
        }
        if (equipment.getMeasurementUnit() != null) {
            existingEquipment.setMeasurementUnit(equipment.getMeasurementUnit());
        }
        if (equipment.getVideoStreamUrl() != null) {
            existingEquipment.setVideoStreamUrl(equipment.getVideoStreamUrl());
        }

        // 保存更新后的设备信息
        return dao.save(existingEquipment);
    }

    /**
     * 保存设备信息
     */
    public Equipment saveEquipment(Equipment equipment, Long plantationId) throws Exception {
        // 验证必填字段
        if (equipment.getEquipmentName() == null || equipment.getEquipmentName().trim().isEmpty()) {
            throw new Exception("设备名称不能为空");
        }

        // 查找并设置大棚
        Plantation plantation = plantationDao.findById(plantationId)
                .orElseThrow(() -> new Exception("大棚不存在"));
        equipment.setPlantation(plantation);

        return dao.save(equipment);
    }

    /**
     * 初始化传感器设备
     */
    public void initializeSensors(Long plantationId) throws Exception {
        Plantation plantation = plantationDao.findById(plantationId)
                .orElseThrow(() -> new Exception("大棚不存在"));

        // 只创建需要的设备列表
        List<Equipment> equipments = Arrays.asList(
                // NPK传感器
                createEquipment("327061430532576242", "土壤氮含量", "nitrogen", "mg/kg", "300023040198", plantation),
                createEquipment("327061430532576243", "土壤磷含量", "phosphorus", "mg/kg", "300023040198", plantation),
                createEquipment("327061430532576244", "土壤钾含量", "potassium", "mg/kg", "300023040198", plantation),

                // 温湿度传感器
                createEquipment("327061430532576247", "空气温度", "temperature", "℃", "300023040198", plantation),
                createEquipment("327061430532576248", "空气相对湿度", "humidity", "%RH", "300023040198", plantation)
        );

        // 保存所有设备
        for (Equipment equipment : equipments) {
            // 检查设备是否已存在
            if (!equipmentDao.findByEquipmentSerial(equipment.getEquipmentSerial()).isPresent()) {
                equipmentDao.save(equipment);
            }
        }
    }

    public Equipment createEquipment(String equipmentSerial, String equipmentName, String equipmentType,
                                      String measurementUnit, String fboxNumber, Plantation plantation) {
        Equipment equipment = new Equipment();
        equipment.setEquipmentSerial(equipmentSerial);
        equipment.setEquipmentName(equipmentName);
        equipment.setEquipmentType(equipmentType);
        equipment.setMeasurementUnit(measurementUnit);
        equipment.setFboxNumber(fboxNumber);
        equipment.setPlantation(plantation);
        return equipment;
    }
}